package com.wtwd.campus.hxy.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.push.model.v20160801.CheckDevicesResponse;
import com.netflix.discovery.converters.Auto;
import com.wtwd.campus.entity.DeviceClassMode;
import com.wtwd.campus.hxy.constant.RespCode;
import com.wtwd.campus.hxy.dao.DeviceMapper;
import com.wtwd.campus.hxy.dao.HxyClassPatternMapper;
import com.wtwd.campus.hxy.dao.HxyCommandRecordMapper;
import com.wtwd.campus.hxy.dao.OfflineBufferCmdMapper;
import com.wtwd.campus.hxy.entity.DeviceInfo;
import com.wtwd.campus.hxy.model.vo.ResultVO;
import com.wtwd.campus.hxy.service.HxyClassPatternService;
import com.wtwd.campus.service.RedisService;
import com.wtwd.campus.utils.CommandNumberUtil;
import com.wtwd.campus.utils.CommandSendUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.schema.Entry;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author mjy
 * @date 2021/07/29
 * @description
 */
@Service
public class HxyClassPatternServiceImpl implements HxyClassPatternService {

    @Autowired
    private HxyClassPatternMapper hxyClassPatternMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private CommandSendUtils commandSendUtils;


    @Override
    public Object setClassPattern(String imei, Integer swit, List<Map> data) {
        DeviceInfo deviceInfo = deviceMapper.getDeviceInfoByImei(imei);
        if (deviceInfo == null) {
            return ResultVO.error(RespCode.DEVICE_NO_EXIST);
        }
        boolean isOnline = commandSendUtils.deviceOnline(imei);
        if (!isOnline) {
            return ResultVO.error(RespCode.DEVICE_IS_OFFLINE);
        }
        // 先查出原有多少条，再判断当前条数。（根据结果决定数据库数据及发送数据、遍历次数按大的为准）
        List<DeviceClassMode> deviceClassModeList = hxyClassPatternMapper.getDeviceModeListByDeviceId(deviceInfo.getDeviceId());
        int forCount = deviceClassModeList.size() > data.size() ? deviceClassModeList.size() : data.size();
        List<DeviceClassMode> sendList = new ArrayList<>();
        // 1.清除原有的课堂模式
        hxyClassPatternMapper.clearClassPattern(deviceInfo.getDeviceId());
        // 2. 解析数据、转成想要的格式
        List<Map<String, Object>> myDataList = parseData(data);
        if (myDataList.size() > 10) {
            return ResultVO.error(RespCode.DEVICE_CLASS_PATTERN_CEILING);
        }
        // 3.循环。判断需要发送的数据及构建需要保存的数据
        for (int i = 0; i < forCount; i++) {
            if (data.size() < i + 1) {
                // 取默认关闭的发送过去
                DeviceClassMode deviceClassMode = new DeviceClassMode();
                deviceClassMode.setStartTime("01:00");
                deviceClassMode.setEndTime("02:00");
                deviceClassMode.setRepeatTime("0000000");
                deviceClassMode.setSequence(i + 1);
                deviceClassMode.setCommandNumber(CommandNumberUtil.getCurTime());
                sendList.add(deviceClassMode);
                if (swit == 1) {
                    commandSendUtils.addClassMode(deviceClassMode, true, -3, false);
                }
            } else {
                // 取带过来的参数转的发过去
                Map<String, Object> myData = myDataList.get(i);
                String beginTime = (String) myData.get("beginTime");
                String endTime = (String) myData.get("endTime");
                String repeatTime = (String) myData.get("repeatTime");
                // 构建对象及指令
                DeviceClassMode deviceClassMode = new DeviceClassMode();
                deviceClassMode.setStartTime(beginTime);
                deviceClassMode.setEndTime(endTime);
                deviceClassMode.setRepeatTime(repeatTime);
                String commandNumber = CommandNumberUtil.getCurTime();
                deviceClassMode.setCommandNumber(commandNumber);
                deviceClassMode.setDeviceId(deviceInfo.getDeviceId());
                deviceClassMode.setSequence(i + 1);
                deviceClassMode.setStatus(2);
                deviceClassMode.setImei(imei);
                deviceClassMode.setOnOff(swit);
                if (swit == 1) {
                    commandSendUtils.addClassMode(deviceClassMode, true, -3, false);
                }
                // 添加到数据库
                hxyClassPatternMapper.saveClassPattern(deviceClassMode);
            }
        }
        // 4.发送总开关
        commandSendUtils.updateClassModeAllSwitch(deviceInfo.getImei(), CommandNumberUtil.getCurTime(), swit, true, -3, false);
        return ResultVO.okWithOutData();
    }

    @Override
    public Object getClassPatternList(String imei) {
        DeviceInfo deviceInfo = deviceMapper.getDeviceInfoByImei(imei);
        if (deviceInfo == null) {
            return ResultVO.error(RespCode.DEVICE_NO_EXIST);
        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        List<DeviceClassMode> deviceModeList = hxyClassPatternMapper.getDeviceModeListByDeviceId(deviceInfo.getDeviceId());
        Map<String, List<DeviceClassMode>> collect = deviceModeList.stream().collect(Collectors.groupingBy(DeviceClassMode::getRepeatTime));
        for (Map.Entry<String, List<DeviceClassMode>> entry : collect.entrySet()) {
            // 将repeatTime转为0,1,2这种
            Map<String, Object> map = new HashMap<>();
            int week = repeatTime2Week(entry.getKey());
            List<Map<String,Object>> timeList = new ArrayList<>();
            for(DeviceClassMode classMode : entry.getValue()){
                Map<String,Object> time = new HashMap<>();
                time.put("beginTime",classMode.getStartTime());
                time.put("endTime",classMode.getEndTime());
                timeList.add(time);
            }
            map.put("sweek",week);
            map.put("time",timeList);
            resultList.add(map);
        }
        Map<String,Object> result = new HashMap<>();
        result.put("code",0);
        result.put("message","操作成功");
        result.put("data",resultList);
        int swit = 0;
        if(deviceModeList != null && deviceModeList.size() > 0){
            swit = deviceModeList.get(0).getOnOff();
        }
        result.put("swit",swit);
        return result;
    }

    private int repeatTime2Week(String repeatTime) {
        int i = repeatTime.indexOf("1");
        if (i == 6) {
            return 0;
        } else {
            return i + 1;
        }

    }

    /**
     * 时间周期转换工具
     *
     * @param week
     * @return
     */

    public String parse2RepeatTime(int week) {
        String repeatTime = "";
        switch (week) {
            case 0:
                repeatTime = "0000001";
                break;
            case 1:
                repeatTime = "1000000";
                break;
            case 2:
                repeatTime = "0100000";
                break;
            case 3:
                repeatTime = "0010000";
                break;
            case 4:
                repeatTime = "0001000";
                break;
            case 5:
                repeatTime = "0000100";
                break;
            case 6:
                repeatTime = "0000010";
                break;

        }
        return repeatTime;
    }

    /**
     * 转成自己想要的数据
     *
     * @param data
     * @return
     */
    private List<Map<String, Object>> parseData(List<Map> data) {
        List<Map<String, Object>> myDataList = new ArrayList<>();
        for (Map map : data) {
            int week = (int) map.get("sweek");
            String repeatTime = parse2RepeatTime(week);
            List<Map<String, Object>> times = (List<Map<String, Object>>) map.get("time");
            for (Map<String, Object> map1 : times) {
                Map<String, Object> myData = new HashMap<>();
                myData.put("beginTime", map1.get("beginTime"));
                myData.put("endTime", map1.get("endTime"));
                myData.put("repeatTime", repeatTime);
                myDataList.add(myData);
            }
        }
        return myDataList;
    }

}
